package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.PosConsts;
import com.iwhalecloud.bss.kite.common.constant.TableConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.util.AcceptUtils;
import com.iwhalecloud.bss.kite.cucc.order.util.OrderRelUtil;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteAttrConfig;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItemAttr;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOrderItemAttr;
import com.iwhalecloud.bss.kite.manager.util.ManagerUtils;
import com.iwhalecloud.bss.kite.order.client.context.OrderContext;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.ztesoft.bss.base.staticdata.CoreDataInteract;
import com.ztesoft.bss.order.base.consts.IKeyValues;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单受理流程：订单项属性处理
 */
@Component
public class OrderItemAttrHandler extends AbstractOrderHandler {

    @Resource
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void doHandle(OrderRequest request) {
        // 处理对应订单项属性及通用属性
        dealTargetOrderItemAttr(request);

        // 处理公共属性配置kiteAttrConfig属性
        dealOrderItemAttrComm(request);
    }

    private void dealTargetOrderItemAttr(OrderRequest request) {
        Map<String, List<KiteOrderItemAttr>> kiteOrderItemAttrMap = request.getSceneInstIds().stream()
                .flatMap(t -> querySceneInstService.listOrderItemAttrs(t).stream())
                .collect(Collectors.groupingBy(t -> ManagerUtils.join(t.getInstType(), t.getInstId())));
        List<KiteOrderItemAttr> commonOrderItemattrs = new ArrayList<>();
        List<String> sceneInstIds = OrderContext.getOrderRequest().getSceneInstIds();
        for (String sceneInstId : sceneInstIds) {
            List<KiteOrderItemAttr> tempOrderItemAttrs = querySceneInstService.getExtParameterValue(sceneInstId,
                    KeyConsts.COMMON_ORDER_ITEM_ATTR);
            if (!KiteListUtils.isEmpty(tempOrderItemAttrs)) {
                commonOrderItemattrs.addAll(tempOrderItemAttrs);
            }
        }

        OrderContainer.ofRequest(request).listOrderItems().forEach(orderItem -> {
            String objId = orderItem.getObjId();
            InstType instType = AcceptUtils.getOfferInstType(orderItem.getOfferKind());
            if (KeyConsts.OFFER_TYPE_10.equals(orderItem.getOfferKind())) {
                objId = request.getInstContainer().getProdInstMap().get(orderItem.getObjId()).getProdInstId();
                instType = InstType.PROD_INST;
            }
            List<OrderItemAttr> orderItemAttrs = kiteOrderItemAttrMap
                    .getOrDefault(ManagerUtils.join(instType, objId), Collections.emptyList()).stream()
                    .map(kiteOrderItemAttr -> {
                        return getOrderItemAttr(kiteOrderItemAttr, orderItem);
                    }).collect(Collectors.toList());
            // 通用属性
            orderItemAttrs.addAll(getCommonOrderItemAttr(commonOrderItemattrs, orderItem));
            OrderContainer.ofRequest(request).addOrderItemAttrs(orderItemAttrs);
        });
    }

    /**
     * 通过配置表进行处理公共属性值入库orderItemAttr
     * @param request
     */
    private void dealOrderItemAttrComm(OrderRequest request) {
        List<OrderItem> orderItems = OrderContainer.ofRequest(request).listOrderItems();
        Map<String, List<OrderItemAttr>> orderItemAttrMap = OrderContainer.ofRequest(request).getOrderContainer().getOrderItemAttrMap();

        orderItems.forEach(t -> {
            orderItemAttrMap.computeIfAbsent(t.getOrderItemId(),  key -> Lists.newArrayList()).addAll(createOrderItemAttrs(t));
        });
    }

    private List<OrderItemAttr>  createOrderItemAttrs(OrderItem orderItem) {
        List<String> sceneInstIds = OrderContext.getOrderRequest().getSceneInstIds();
        List<KiteAttr> kiteAttrs = new ArrayList<>();
        List<OrderItemAttr> assemblyAttrs = new ArrayList<>();
        if (KiteListUtils.isNotEmpty(sceneInstIds)) {
            for (String sceneInstId : sceneInstIds) {
                kiteAttrs.addAll(querySceneInstService.listCommonAttrs(sceneInstId));
            }
        }
        OrderRequest orderRequest = OrderContext.getOrderRequest();
        String serviceOfferId = orderRequest.getServiceOfferId();
        for (KiteAttr attr : kiteAttrs) {
            if (KiteStringUtils.isEmpty(attr.getValue())) {
                continue;
            }

            KiteAttrConfig existConfig = OrderRelUtil.isExistTable(attr.getFieldName(), serviceOfferId, TableConsts.OrderItemAttr.getTableName());
            if (null != existConfig) {
                assemblyAttrs.add(addOrderItemAttr(attr, orderItem));
            }
        }

        return assemblyAttrs;
    }

    private OrderItemAttr addOrderItemAttr(KiteAttr kiteAttr, OrderItem orderItem) {
        OrderItemAttr orderIteAttr = new OrderItemAttr();
        orderIteAttr.setFieldName(kiteAttr.getFieldName());
        orderIteAttr.setpFieldName(kiteAttr.getFieldName());
        orderIteAttr.setAttrId(StringUtils.isNotBlank(kiteAttr.getAttrId()) ? kiteAttr.getAttrId() : "-1");
        orderIteAttr.setAttrValue(kiteAttr.getValue());
        orderIteAttr.setOrderId(orderItem.getCustOrderId());
        orderIteAttr.setOrderItemId(orderItem.getOrderItemId());
        orderIteAttr.setCustId(orderItem.getBelongCustId());
        orderIteAttr.setCreateStaff(orderItem.getCreateStaff());
        orderIteAttr.setCreateDate(orderItem.getCreateDate());
        orderIteAttr.setStatusDate(orderIteAttr.getCreateDate());
        orderIteAttr.setUpdateDate(orderIteAttr.getCreateDate());
        orderIteAttr.setpOrderAttrId(orderIteAttr.getAttrId());
        orderIteAttr.setAttrCd(kiteAttr.getAttrId());
        orderIteAttr.setOrderType(IKeyValues.ORDER_TYPE_ORDERITEM);
        orderIteAttr.setStatusCd(CoreDataInteract.EVT_C_0014_1000);
        orderIteAttr.setVerNum("0");
        orderIteAttr.setOrderItemAttrId(SeqUtils.getNext(TableConsts.OrderItemAttr));
        return orderIteAttr;
    }


    /**
     * 生成订单项属性
     * @param kiteOrderItemAttr
     * @param orderItem
     * @return
     */
    private OrderItemAttr getOrderItemAttr(KiteOrderItemAttr kiteOrderItemAttr, OrderItem orderItem) {
        OrderItemAttr orderItemAttr = new OrderItemAttr();
        orderItemAttr.setFieldName(kiteOrderItemAttr.getFieldName());
        orderItemAttr
            .setpFieldName(StringUtils.isNotBlank(kiteOrderItemAttr.getPFieldName()) ? kiteOrderItemAttr.getPFieldName()
                : kiteOrderItemAttr.getFieldName());
        orderItemAttr
            .setAttrId(StringUtils.isNotBlank(kiteOrderItemAttr.getAttrId()) ? kiteOrderItemAttr.getAttrId() : "-1");
        orderItemAttr.setAttrValue(kiteOrderItemAttr.getAttrValue());
        orderItemAttr.setOrderId(orderItem.getCustOrderId());
        orderItemAttr.setOrderItemId(orderItem.getOrderItemId());
        orderItemAttr.setCustId(orderItem.getBelongCustId());
        orderItemAttr.setCreateStaff(orderItem.getCreateStaff());
        orderItemAttr.setCreateDate(orderItem.getCreateDate());
        orderItemAttr.setStatusDate(orderItemAttr.getCreateDate());
        orderItemAttr.setUpdateDate(orderItemAttr.getCreateDate());
        orderItemAttr.setpOrderAttrId(orderItemAttr.getAttrId());
        orderItemAttr.setAttrCd(kiteOrderItemAttr.getAttrId());
        orderItemAttr.setOrderType(IKeyValues.ORDER_TYPE_ORDERITEM);
        orderItemAttr.setStatusCd(CoreDataInteract.EVT_C_0014_1000);
        orderItemAttr.setVerNum("0");
        orderItemAttr.setOrderItemAttrId(SeqUtils.getNext(TableConsts.OrderItemAttr));
        return orderItemAttr;
    }

    /**
     * 设置极简受理订单标识，组装通用订单项属性
     * @param orderItem
     * @return
     */
    private List<OrderItemAttr> getCommonOrderItemAttr(List<KiteOrderItemAttr> commonOrderItemattrs, OrderItem orderItem) {
        List<OrderItemAttr> orderItemAttrs = new ArrayList<>();
        KiteOrderItemAttr acceptFlagAttr = new KiteOrderItemAttr();
        acceptFlagAttr.setFieldName(PosConsts.KITE_ORDER_FIELD_CODE);
        acceptFlagAttr.setPFieldName(PosConsts.KITE_ORDER_FIELD_CODE);
        acceptFlagAttr.setAttrValue(KeyConsts.IFTRUE_T);
        orderItemAttrs.add(getOrderItemAttr(acceptFlagAttr, orderItem));
        if (!KiteListUtils.isEmpty(commonOrderItemattrs)) {
            for (KiteOrderItemAttr itemAttr : commonOrderItemattrs) {
                orderItemAttrs.add(getOrderItemAttr(itemAttr, orderItem));
            }
        }
        return orderItemAttrs;
    }
}
